# history/views.py
import csv
import datetime
import json
import os
import uuid

from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

from .models import HistoryRecord


@csrf_exempt
def get_all_history(request):
    data = list(HistoryRecord.objects.values())
    return JsonResponse(data, safe=False)


# 确保 CSV 文件保存目录存在
SAVE_DIR = os.path.join(settings.BASE_DIR, 'templates')
os.makedirs(SAVE_DIR, exist_ok=True)


@csrf_exempt
@require_http_methods(["POST"])
def save_history_record(request):
    try:
        body = json.loads(request.body)
        task_name = body.get('taskName')
        records = body.get('records')

        if not task_name or not isinstance(records, list) or not all(
                isinstance(row, list) and len(row) == 3 for row in records):
            return JsonResponse(
                {'error': 'Invalid format: taskName must be string and records must be list of 3-item arrays.'},
                status=400)

        # 生成唯一文件名
        file_name = f"{uuid.uuid4().hex}.csv"
        file_path = os.path.join(SAVE_DIR, file_name)

        # 写入 CSV 文件
        with open(file_path, mode='w', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            writer.writerow(['azimuth', 'elevation', 'distance'])
            writer.writerows(records)

        # 写入数据库
        relative_path = os.path.relpath(file_path, settings.BASE_DIR)
        record = HistoryRecord.objects.create(
            name=task_name,
            path=relative_path,
            record_time=datetime.datetime.now()
        )

        return JsonResponse({'message': 'Saved successfully', 'id': record.id})

    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)